package com.cy.store.controller;

import com.cy.store.controller.ex.*;
import com.cy.store.entity.User;
import com.cy.store.service.IUserService;

import com.cy.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * @author ZhangSir
 */
@RestController
@RequestMapping("/users")
public class UserController extends BaseController{

    @Autowired
    private IUserService userService;

    // 设置文件的大小范围，不能超过10MB
    public static final int Avatar_Max_Size = 10*1024*1024;

    /* 用户注册 */
    @RequestMapping(value = "/reg",method = POST)
    public JsonResult<Void> reg(User user){
        userService.reg(user);
        return new JsonResult<>(OK);
    }

    /* 用户登录 */
    @RequestMapping(value = "/login",method = POST)
    public JsonResult<User> login(String username, String password, HttpSession session){
        User data = userService.login(username,password);
        // 向session对象中完成数据的绑定
        session.setAttribute("uid",data.getUid());
        session.setAttribute("username",data.getUsername());
        return new JsonResult<>(OK,data);
    }

    /* 修改密码 */
    @RequestMapping(value = "/change_password",method = POST)
    public JsonResult<Void> changePassword(String oldPassword,String newPassword,HttpSession session){
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        userService.changePassword(uid,username,oldPassword,newPassword);
        return new JsonResult<>(OK);
    }

    /* 通过用户名获取用户信息 */
    @RequestMapping(value = "/getByUsername",method = GET)
    public JsonResult<User> getByUsername(String username){
        User data = userService.findByUsername(username);
        return new JsonResult<>(OK ,data);
    }

    /* 获取用户信息 */
    @RequestMapping(value = "/getByUid",method = GET)
    public JsonResult<User> getUserByUid(HttpSession session){
        Integer uid = getUidFromSession(session);
        User data = userService.findByUid(uid);
        return new JsonResult<>(OK ,data);
    }
    // 设置文件的类型，这里定义为列表，后续可以调用列表的contains方法做判断
    public static final List<String> typeList = new ArrayList<>();
    // 集合用来存储支持用户上传的文件格式，放在 static 静态代码块初始化
    static {
        typeList.add("image/jpeg");
        typeList.add("image/png");
        typeList.add("image/gif");
        typeList.add("image/bmp");
    }

    /* 用户修改个人资料 */
    @RequestMapping(value = "/changeInfo", method = POST)
    public JsonResult<Void> changeInfo(User user,HttpSession session){
        // user对象中要四个数据，username,phone,email,gender
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        userService.changeInfo(uid,username,user);
        return new JsonResult<>(OK);
    }

    /* 用户上传头像接口 */
    @RequestMapping(value = "/changeAvatar",method = POST)
    public JsonResult<String> changeAvatar(HttpSession session,
                                           @RequestParam("file") MultipartFile file){
        // 文件判空
        if (file.isEmpty()){
            throw new FileEmptyException("文件为空");
        }
        // 文件大小判断
        if (file.getSize() > Avatar_Max_Size){
            throw new FileSizeException("文件大小不符合要求");
        }
        // 文件类型判断
        String type = file.getContentType();
        if (!typeList.contains(type)){
            throw new FileTypeException("文件类型不对");
        }
        // 文件上传
        String parent = session.getServletContext().getRealPath("upload");
        // 判断目录是否存在，不存在则创建
        File dir = new File(parent);
        if (!dir.exists()){
            dir.mkdir();
        }
        // 获取文件全名
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        // 生成新的文件后缀名
        String suffix = originalFilename.substring(index);
        // 生成新的文件前缀名,使用UUID生成随机字符串，保持文件名称唯一,防止出现文件覆盖
        String filename = UUID.randomUUID().toString().toUpperCase()+suffix;
        File dest = new File(dir,filename);
        try {
            file.transferTo(dest);
        } catch (FileStateException e) {
            throw new FileStateException("文件状态异常");
        } catch (IOException e) {
            throw new FileUploadIoException("文件读写异常");
        }
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        // 返回头像路径
        String avatar = "/upload/"+filename;
        userService.changeAvatar(uid,avatar,username);
        return new JsonResult<>(OK,avatar);
    }

}
